import { login, userSelector } from ':/store/selice/user';
import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import './index.less';
import { ELoading } from ':/const/status';
import { useLocation, useNavigate } from 'react-router';
import { ERoutePath } from ':/routes/const';

const LoginPage = () => {
  const dispatch = useDispatch();
  const [username, setUserName] = useState('');
  const [password, setPassword] = useState('');
  const userState = useSelector(userSelector.selectState);
  const navigate = useNavigate();
  const location = useLocation();

  useEffect(() => {
    if (userState.loading === ELoading.LOADED && userState.data) {
      navigate(location.state?.redirect || ERoutePath.HOME);
    }
  }, [userState]);

  return (
    <div className="login-page">
      <div className="login-form">
        <div>{userState.loading}</div>
        <label className="form-item">
          <span className="form-item-label">用户名</span>
          <input
            className="form-item-input"
            type="text"
            name="username"
            placeholder="请输入用户名"
            value={username}
            onChange={e => setUserName(e.target.value)}
          />
        </label>
        <label className="form-item">
          <span className="form-item-label">密码</span>
          <input
            className="form-item-input"
            type="password"
            name="pasword"
            placeholder="请输入登录密码"
            value={password}
            onChange={e => setPassword(e.target.value)}
          />
        </label>
        <button className="submit-btn" onClick={() => {
          dispatch(login({ username, password }));
        }}>登录</button>
      </div>
    </div>
  )
}

export default LoginPage;